package com.example.hello.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

@MappedTypes(LocalDateTime.class)
public class ZeroDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            return rs.getObject(columnName, LocalDateTime.class);
        } catch (SQLException e) {
            // 处理零日期值的异常
            if (e.getMessage().contains("Zero date value prohibited")) {
                return null;
            }
            throw e;
        }
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            return rs.getObject(columnIndex, LocalDateTime.class);
        } catch (SQLException e) {
            // 处理零日期值的异常
            if (e.getMessage().contains("Zero date value prohibited")) {
                return null;
            }
            throw e;
        }
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            return cs.getObject(columnIndex, LocalDateTime.class);
        } catch (SQLException e) {
            // 处理零日期值的异常
            if (e.getMessage().contains("Zero date value prohibited")) {
                return null;
            }
            throw e;
        }
    }
} 